package com.example.springboot2.base.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot2.oa.entity.TUser;
import com.example.springboot2.oa.service.ITUserService;
import com.example.springboot2.tools.MakeResponse;
import com.example.springboot2.tools.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

public class BaseController {
    /**
     * 注入userService
     */
    @Autowired
    protected ITUserService userService;
    public TUser getUser(String token) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("token", token);
        return userService.getOne(wrapper);
    }

    public TUser getUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        return getUser(token);
    }

    public ResponseMessage authentication(String token) {
        return authentication(token, null);
    }

    public ResponseMessage authentication(HttpServletRequest request) {
        return authentication("", request);
    }

    public ResponseMessage authentication(String token, HttpServletRequest request) {
        if (token.equals("") && request != null) {
            token = request.getHeader("token");
        }

        if (getUser(token) == null) {
            return MakeResponse.success("401", "无权限访问");
        }

        return null;
    }
}
